package com.tledu.controller;

import com.tledu.core.AjaxResult;
import com.tledu.model.Employee;
import com.tledu.service.EmployeeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("employee")
@Controller
@AllArgsConstructor
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;



    @RequestMapping("/login")
    public String login() {
        return "login";
    }


    @GetMapping("/list")
    public String emp(ModelMap modelMap) {
        List<Employee> employeesList = employeeService.list();
        modelMap.addAttribute("employeesList",employeesList);
        return "employee/employee-list";
    }


    @DeleteMapping("/delete")
    @ResponseBody
    public AjaxResult<Employee> delete(String id){
        int i = employeeService.delete(id);
        if (i != 1){
            return new AjaxResult<Employee>(false,"删除失败");
        }
        return new AjaxResult<Employee>(true,"删除成功");
    }


    @PostMapping("/add")
    @ResponseBody
    public AjaxResult<Employee> insert(@RequestBody Employee employee){
        int i = employeeService.insert(employee);
        System.out.println(employee);
        if (i != 1){
            return new AjaxResult<Employee>(false,"添加失败");
        }
        return new AjaxResult<Employee>(true,"添加成功");
    }

    @GetMapping("/add")
    public String toAddJsp(){
        return "employee/employee-add";
    }



    @GetMapping("/edit")
    public String toEditJsp(String id,ModelMap modelMap){
        Employee employee = employeeService.selectById(id);
        modelMap.addAttribute("employee",employee);
        return "employee/employee-edit";
    }



    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult<Employee> update(@RequestBody  Employee employee){
        System.out.println(employee);
        int i = employeeService.update(employee);

        if (i != 1){
            return new AjaxResult<Employee>(false,"修改失败,不能修改编号");
        }
        return new AjaxResult<Employee>(true,"修改成功");
    }



}
